package com.gxgeek.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author gaoxing
 * @create 2017-12-19 上午11:44
 */
public class CachedData {
    Object data;
    volatile boolean cacheValid;
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public CachedData() {
//        cacheValid = true;
    }

    void processData(Object expect) {
        readWriteLock.readLock().lock();
        if (!cacheValid) {
            System.out.println("修改前的数据为: " + data);
            readWriteLock.readLock().unlock();

            readWriteLock.writeLock().lock();
            if (!cacheValid) {
                data = expect;
                cacheValid  =true ;
            }


            readWriteLock.writeLock().unlock();
            readWriteLock.readLock().lock();
        }

        System.out.println("修改后的数据为: " + data);

        readWriteLock.readLock().unlock();
    }

    public static void main(String[] args) {
        final CachedData cachedData = new CachedData();

        Runnable worker = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    cachedData.processData(Thread.currentThread().getName() + " is working");
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            }
        };

        for (int i = 0; i < 2; i++) {
            Thread testThread = new Thread(worker, "worker" + i);
            testThread.start();
        }

        try {
            // 休息一秒后
            Thread.sleep(1000);
            cachedData.cacheValid = false;
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}
